package apihandler

import (
	"flag"
	"github.com/gin-gonic/gin"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"log"
	"zg4zk3/api-way/apirequest"
	"zg4zk3/api-way/basic/pkg"
	__ "zg4zk3/api-way/basic/proto"
	client2 "zg4zk3/srv/client"
	"zg4zk3/srv/dao"
)

func List(context *gin.Context) {
	var req apirequest.ListReq
	err := context.ShouldBind(&req)
	if err != nil {
		context.JSON(200, gin.H{
			"code": 200,
			"msg":  nil,
			"data": err.Error(),
		})
		return
	}
	flag.Parse()
	// Set up a connection to the server.
	conn, err := grpc.NewClient("localhost:50051", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()
	client := __.NewUserClient(conn)
	List, err := client.List(context, &__.ListRequest{})

	if err != nil {
		return
	}

	var good []client2.Goods
	dao.List(&good)

	context.JSON(200, gin.H{
		"code": 200,
		"msg":  List,
		"data": good,
	})
}

func Show(context *gin.Context) {

	var req apirequest.ShowReq
	err := context.ShouldBind(&req)
	if err != nil {
		context.JSON(200, gin.H{
			"code": 200,
			"msg":  nil,
			"data": err.Error(),
		})
		return

	}
	flag.Parse()
	// Set up a connection to the server.
	conn, err := grpc.NewClient("localhost:50051", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()

	client := __.NewUserClient(conn)
	show, err := client.Show(context, &__.ShowRequest{
		Id: int64(req.Id),
	})
	if err != nil {
		return
	}

	var good client2.Goods
	dao.Show(req.Id, &good)

	context.JSON(200, gin.H{
		"code": 200,
		"msg":  show,
		"data": good,
	})

}

func Upload(context *gin.Context) {
	file, _ := context.FormFile("file")
	log.Println(file.Filename)

	dst := "D:\\goWork\\wenjian\\million\\zg4rk\\zg4zk3\\api-way\\statis" + file.Filename
	// 上传文件至指定的完整文件路径
	pkg.Upload(dst)
	err := context.SaveUploadedFile(file, "D:\\goWork\\wenjian\\million\\zg4rk\\zg4zk3\\api-way\\statis"+file.Filename)
	if err != nil {
		return
	}
}
